// pages/entry/index.js
const md5 = require("../../utils/md5")
import {
  fileUrl,
} from "../network/index"
import ajax from '../network/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [{
      type: '1', //1借  2贷
      subjectCode: "",
      subjectName: "",
      amount: "",
      memo: "",
      img: [],

    }],
    enterTotal: '0.00',
    outTotal: '0.00',
  },
  toChoiceSubject(e) {
    let index = e.currentTarget.dataset.index
    let code = e.currentTarget.dataset.code
    let name = e.currentTarget.dataset.name
    wx.navigateTo({
      url: '/pages/entry/choiceList?index=' + index + '&code=' + code + '&name=' + name,
    })
  },
  radioChange(e) {
    let list = this.data.list
    let index = e.currentTarget.dataset.index
    list[index].type = e.detail.value
    this.getTotal()
  },
  bindIpt(e) {
    let list = this.data.list
    let index = e.currentTarget.dataset.index
    list[index].amount = e.detail.value
    this.getTotal()
  },
  getTotal() {
    let list = this.data.list
    var enterTotalList = list.map(item => {
      if (item.type == 1) {
        return item.amount
      }
    }).filter(items => items)
    var outTotalList = list.map(item => {
      if (item.type == 2) {
        return item.amount
      }
    }).filter(items => items)
    var enterTotal = 0
    var outTotal = 0
    if (enterTotalList && enterTotalList.length) {
      enterTotalList.forEach(item => {
        enterTotal += Number(item)
      })
    }
    if (outTotalList && outTotalList.length) {
      outTotalList.forEach(item => {
        outTotal += Number(item)
      })
    }
    this.setData({
      enterTotal: enterTotal.toFixed(2),
      outTotal: outTotal.toFixed(2),
    })
    this.saveCache()
  },
  bindMemoIpt(e) {
    let list = this.data.list
    let index = e.currentTarget.dataset.index
    list[index].memo = e.detail.value
    this.saveCache()
  },
  //上传图片
  pricture(e) {
    let _this = this
    let list = this.data.list
    let index = e.currentTarget.dataset.index
    let inventoryPicture = list[index].img
    //保存本地预览图
    wx.chooseImage({
      count: 10,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      complete(e) {

      },
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        //获取文件大小
        let ratio = 80
        tempFilePaths.forEach(element => {
          if (element.size > 20971520) {
            wx.showToast({
              title: '图片限制为20M',
              icon: "none",
            })
            return
          } else if (element.size > 10485760)
            ratio = 10
          else if (element.size > 5242880 && element.size < 10485760) {
            ratio = 20
          }
          //压缩图片，只能在真机上使用，模拟器不支持

          wx.compressImage({
            src: element.path,
            quality: ratio,
            success: function (res) {
              wx.showLoading({
                title: '图片上传中...',
                mask: true
              })
              wx.uploadFile({
                filePath: res.tempFilePath,
                name: 'img',
                url: fileUrl,
                success: function (v) {
                  wx.hideLoading({
                    success: (res) => {},
                  })

                  if (v.statusCode != 200) {
                    wx.showToast({
                      icon: "none",
                      title: '图片上传失败',
                    })
                    return
                  }
                  let imageUrl = JSON.parse(v.data).data
                  inventoryPicture.push(imageUrl)
                  _this.setData({
                    list
                  })
                  _this.saveCache()
                },
                fail: function () {
                  wx.showToast({
                    title: '图片上传失败',
                    icon: "none",
                  })
                }
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '图片压缩失败',
                icon: "none",
              })
            }
          })
        })
      },
      fail: function (v) {
        wx.showToast({
          title: '打开相机失败',
          icon: "none",
        })
      }
    })
  },
  preview(e) {
    // 预览图片
    //该任务的下标
    let previewUrl = e.currentTarget.dataset.image
    let list = this.data.list
    let index = e.currentTarget.dataset.index
    let urls = list[index].img
    wx.previewImage({
      current: previewUrl,
      urls
    })
  },
  delPicture(e) {
    wx.showModal({
      title: "温馨提示",
      content: "是否确认删除该图片",
      success: res => {
        if (res.confirm) {
          let list = this.data.list
          let fatherIndex = e.currentTarget.dataset.fatherindex
          let index = e.currentTarget.dataset.index
          list[fatherIndex].img.splice(index, 1)
          this.setData({
            list
          })
          this.saveCache()
        }
      }
    })
  },
  addTask() {
    let list = this.data.list
    list.push({
      type: '1', //1借  2贷
      subjectCode: "",
      subjectName: "",
      amount: "",
      memo: "",
      img: [],
    })
    this.setData({
      list
    })
    this.saveCache()
  },
  delTask(e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let list = this.data.list
    wx.showModal({
      title: '提示',
      content: "是否确认删除？",
      success(res) {
        if (res.confirm) {
          wx.showToast({
            title: '删除成功',
          })
          list.splice(index, 1)
          _this.setData({
            list
          })
          _this.getTotal()
        } else {
          wx.showToast({
            title: '取消删除',
            icon: "none",
          })
        }
      }
    })

    // }
  },
  _confirm() {
    let list = JSON.parse(JSON.stringify(this.data.list))
    if (list && list.length) {
      var flag = list.some(item => !item.subjectCode || !item.subjectName || !item.amount || !item.memo)
      if (flag) {
        wx.showToast({
          title: '科目，金额，备注为必填项，请检查',
          icon: "none"
        })
        return
      }
      wx.showLoading({
        title: '提交中...',
      })
      var enterData = []
      var outData = []
      list.forEach(item => {
        if (item.type == 1) {
          delete item.type
          enterData.push(item)
        } else {
          delete item.type
          outData.push(item)
        }
      })
      ajax({
        url: "/subject/subjectTransferAccounts",
        method: "post",
        data: {
          enterData,
          outData
        }
      }, 'application/json').then(res => {
        wx.hideLoading()
        if (res.code == 200) {
          wx.showModal({
            content: res.msg,
            showCancel: false,
            success: () => {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }
      }).catch(() => {
        wx.hideLoading()
      })



    }
  },
  saveCache() {
    let data = this.data
    wx.setStorageSync('saveCacheEntry', data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let saveCache = wx.getStorageSync('saveCacheEntry')
    //使用md5验证数据是否一样
    let cache = md5.hexMD5(JSON.stringify(saveCache))
    let beforeDate = md5.hexMD5(JSON.stringify(this.data))
    let _this = this
    if (saveCache != '') {
      if (cache != beforeDate) {
        wx.showModal({
          title: "提示",
          content: "检测到上次有未提交的数据，是否恢复！",
          success(res) {
            if (res.confirm) {
              _this.setData({
                ...saveCache
              })
            }
            wx.removeStorageSync('saveCacheEntry')
          }
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})